package org.darkforest.merchant.controller;

import org.apache.commons.lang.StringUtils;
import org.darkforest.common.services.StoreExtendsService;
import org.darkforest.common.util.AliOssFileUploadUtil;
import org.darkforest.common.services.DeliverService;
import org.darkforest.dao.mapper.ExpressMapper;
import org.darkforest.dao.mapper.StoreExtendMapper;
import org.darkforest.dao.mapper.StoreMapper;
import org.darkforest.model.*;
import org.darkforest.ucenter.service.AreaRedisService;
import org.darkforest.vo.StoreSellerVo;
import org.darkforest.vo.WapAjaxMsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * Created by chenyu on 15/1/30.
 * 订单物流相关控制类
 */
@Controller
@RequestMapping(value="/deliver")
public class DeliverController {

    @Autowired
    private DeliverService deliverService;
    @Autowired
    private AreaRedisService areaRedisService;
    @Autowired
    private StoreExtendsService storeExtendsService;
    @Autowired
    private StoreMapper storeMapper;
    @Autowired
    private ExpressMapper expressMapper;



    @RequestMapping(value = "deliverSetList")
    public ModelAndView deliverSetList(HttpSession session) {
        StoreSellerVo sellerVo = (StoreSellerVo)session.getAttribute("sellerInfo");
        List addressList = deliverService.selectAddress(sellerVo.getStoreId());
        return new ModelAndView("deliver/deliverSetList","addressList",addressList);
    }


    @RequestMapping(value = "updateSellAddress")
    public ModelAndView updateSellAddress(int addressId) {
        DAddress addressVo = deliverService.selectByPrimaryKey(addressId);
        return new ModelAndView("deliver/updateSellAddress","addressVo",addressVo);
    }


    @RequestMapping(value = "toUpdateSellAddress")
    public ModelAndView toUpdateSellAddress(DAddress address) {
        deliverService.updateAddress(address);
        return new ModelAndView("redirect:/deliver/deliverSetList");
    }

    //删除区域
    @RequestMapping(value = "deleteAddress")
    public ModelAndView deleteAddress(int addressId) {
        deliverService.deleteAddress(addressId);
        return new ModelAndView("redirect:/deliver/deliverSetList");
    }

    //跳转到添加的页面
    @RequestMapping(value = "addSellAddress")
    public ModelAndView addSellAddress() {
        return new ModelAndView("deliver/addSellAddress");
    }


    @RequestMapping(value = "toAddSellAddress")
    public ModelAndView toAddSellAddress(DAddress address,HttpSession session) {
        StoreSellerVo sellerVo = (StoreSellerVo)session.getAttribute("sellerInfo");
        address.setStoreId(sellerVo.getStoreId());
        // address.setSellerName(sellerVo.getSellerName());
        deliverService.insertAddress(address);
        return new ModelAndView("redirect:/deliver/deliverSetList");
    }

    //修改默认的地址。
    @RequestMapping(value = "updateDefault")
    public ModelAndView updateDefault(int addressId,HttpSession session) {
        StoreSellerVo sellerVo = (StoreSellerVo)session.getAttribute("sellerInfo");
        List addressList = deliverService.selectAddress(sellerVo.getStoreId());
        DAddress address = null;
        for(int i=0;i<addressList.size();i++){
            address = (DAddress)addressList.get(i);
            if("1".equals(address.getIsDefault())){
                address.setIsDefault("0");
                deliverService.updateAddress(address);
            }
        }
        DAddress address1 = deliverService.selectByPrimaryKey(addressId);
        address1.setIsDefault("1");
        deliverService.updateAddress(address1);
        return new ModelAndView("redirect:/deliver/deliverSetList");
    }


    @RequestMapping(value = "areaList",method = RequestMethod.POST)
    public @ResponseBody
    WapAjaxMsg<List<Area>> getAddressAreaList(Integer paId){
//        Logger.debug(AddressController.class, "address" + paId);
        WapAjaxMsg<List<Area>> res = new WapAjaxMsg<List<Area>>();
        res.setDatas(areaRedisService.getAreaList(paId==null?null:paId.toString()));
        return res;
    }



    //物流公司
    @RequestMapping(value = "companyList")
    public ModelAndView companyList(Integer paId,HttpSession session){
        StoreSellerVo sellerVo = (StoreSellerVo)session.getAttribute("sellerInfo");
        //List<Express> companyList = deliverService.selectAllExpress();
        // 只有运营端将状态设为1的，商家才可以看到
        Express express = new Express();
        express.seteState("1");
        express.setPageSwitch(false);
        List<Express> companyList = expressMapper.selectByCondition(express);
        StoreExtend storeExtend = storeExtendsService.selectByPrimaryKey(sellerVo.getStoreId());
        if(storeExtend != null && StringUtils.isNotEmpty(storeExtend.getExpress())) {
            String[] storeExpress = storeExtend.getExpress().split(",");
            //循环对比设置物流公司状态
            for (Express eps : companyList) {
                Integer epsId = eps.geteId();
                eps.setIsDefault(0);
                for (int i = 0; i < storeExpress.length; i++) {
                    Integer storeEps = Integer.parseInt(storeExpress[i]);
                    if (epsId == storeEps) {
                        eps.setIsDefault(1);
                    }
                }
            }
        }
        return new ModelAndView("deliver/companyList","companyList",companyList);
    }


    //物流公司

    @RequestMapping(value = "updateEOrder")
    public ModelAndView updateEOrder(String [] eOrderIds,HttpServletRequest request){
        StoreSellerVo sellerVo= (StoreSellerVo)request.getSession().getAttribute("sellerInfo");
//        deliverService.updateDefault();
        if(eOrderIds!=null) {
            List nList = Arrays.asList(eOrderIds);
            // deliverService.updateEOrders(nList);
            StoreExtend storeExtend = new StoreExtend();
            storeExtend.setStoreId(sellerVo.getStoreId());
            String express ="";
            for(int i=0;i<eOrderIds.length;i++){
                express+=eOrderIds[i];
                if(i<eOrderIds.length-1){
                    express+=",";
                }
            }
            storeExtend.setExpress(express);
            StoreExtend se =  storeExtendsService.selectByPrimaryKey(sellerVo.getStoreId());
            if(se == null || !(se.getStoreId().equals(sellerVo.getStoreId()))){
                storeExtendsService.insert(storeExtend);
            }else{
                storeExtendsService.updateByPrimaryKeySelective(storeExtend);
            }
        }
        return new ModelAndView("redirect:/deliver/companyList");
    }

    // 免运费额度
    @RequestMapping(value = "free")
    public ModelAndView free(HttpSession session){
        StoreSellerVo sellerVo = (StoreSellerVo)session.getAttribute("sellerInfo");
        Store store = deliverService.getSoreByid(sellerVo.getStoreId());
        return new ModelAndView("deliver/free","store",store);
    }
    @RequestMapping(value = "updateFree")
    public ModelAndView updateFree(StoreWithBLOBs store){
        int ret =  deliverService.updateStore(store);
        return new ModelAndView("deliver/free","store",store);
    }

    //发货单打印设置
    @RequestMapping(value = "printSet")
    public ModelAndView printSet(HttpSession session){
        StoreSellerVo sellerVo= (StoreSellerVo)session.getAttribute("sellerInfo");
        Store store = storeMapper.selectStoreByPrimaryKey(sellerVo.getStoreId());
        return new ModelAndView("deliver/printSet","store",store);
    }


    //发货单打印设置
    @RequestMapping(value = "updatePrintSet")
    public ModelAndView updatePrintSet(HttpServletRequest request,String store_stamp_old,MultipartFile imgFile,StoreWithBLOBs store){
        store.setStoreStamp(store_stamp_old);
        if(imgFile!=null&&imgFile.getOriginalFilename()!=null&&!"".equals(imgFile.getOriginalFilename())){
            int extIndex = imgFile.getOriginalFilename().lastIndexOf(".");
            String extName =  "";
            if (extIndex > 0) {
                extName =  imgFile.getOriginalFilename().substring(extIndex);
            }
            // 图片文件后缀的判断
            if (!".PNG".equals(extName.toUpperCase()) && !".GIF".equals(extName.toUpperCase())) {
                ModelAndView modelAndView = new ModelAndView("message");
                modelAndView.addObject("msg", "印章图片格式不正确，请选择正确的图片!");
                return modelAndView;
            }
            String name = new Date().getTime() + extName;
            String begin = System.getProperty("user.dir");
            File targetFile = new File(begin,name);
            try {
                imgFile.transferTo(targetFile);
                AliOssFileUploadUtil.uploadPic(new Date().getTime()+"",name,targetFile);
            } catch (IOException e) {
                e.printStackTrace();
                ModelAndView modelAndView = new ModelAndView("message");
                modelAndView.addObject("msg", "印章图片保存失败，请重新提交!");
                return modelAndView;
            }
            store.setStoreStamp(name);
        }
        deliverService.updateStore(store);
        return new ModelAndView("deliver/printSet","store",store);
    }
}
